package com.itheima.controller;

import com.google.code.kaptcha.Producer;
import com.itheima.constant.KeyConstant;
import com.itheima.result.Result;
import com.itheima.service.EmployeeService;
import com.itheima.utils.IdUtils;
import com.itheima.vo.KaptchaCodeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

@Slf4j
@Api(tags = "通用服务")
@RestController
@RequestMapping("/common")
public class CommonController {

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 生成验证码
     */
    @ApiOperation("验证码-生成")
    @GetMapping("/kaptcha")
    public Result getCode(HttpServletResponse response) throws IOException {
        log.info("生成验证码 ");
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = KeyConstant.CAPTCHA_CODE_KEY + uuid;

        String code = captchaProducer.createText(); //生成随机字符
        BufferedImage image = captchaProducer.createImage(code);//生成图片

        redisTemplate.opsForValue().set(verifyKey, code, 5, TimeUnit.MINUTES); //存入redis

        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return Result.error(e.getMessage());
        }

        return Result.success(new KaptchaCodeVo(uuid, Base64.getEncoder().encodeToString(os.toByteArray())));
    }


}
